from opencv import cv
from opencv import highgui
from opencv import adaptors
import gtk
import StringIO
import Image
import AiBlob

def showImage(img):
    highgui.cvNamedWindow ("Image", highgui.CV_WINDOW_AUTOSIZE)
    highgui.cvShowImage ("Image", img)
    highgui.cvWaitKey (0)

def showAiImage(img):
    highgui.cvNamedWindow (img.filename, highgui.CV_WINDOW_AUTOSIZE)
    highgui.cvShowImage (img.filename, img.img)
    highgui.cvWaitKey (0)

def loadImageFromFile(filename):
    aiimage = AiImage(highgui.cvLoadImage(str(filename)))
    return aiimage


class AiImage:
    """
       Wrapper class for opencv Images.
    """

    def __init__(self, i):
        self.img = i

    def clone(self):
        newimg = cv.cvCloneImage(self.img)
        return AiImage(newimg)

    def asGtkPixbuff(self):
        pil = adaptors.Ipl2PIL(self.img)

        file1 = StringIO.StringIO()  
        pil.save(file1, "ppm")  
        contents = file1.getvalue()  
        file1.close()  
        loader = gtk.gdk.PixbufLoader("pnm")  
        loader.write(contents, len(contents))  
        pixbuf = loader.get_pixbuf()  
        loader.close()

        return pixbuf
